#pragma once
#include "data.hpp"
#include "protocol.hpp"
#include "send.hpp"
#include "Funtion.hpp"
#define EPOLL_EVENT_NUM 20
#define TIMEOUT 1000
class EpollServer
{
public:
    EpollServer()
    {
        // 创建套接字
        _sock = _server.CreatSock();
        // 端口复用
        _fun.SetPort(_sock);
        // 非阻塞
        _fun.Setftl(_sock);
        // 绑定端口
        _server.Bind();
        // 监听端口
        _server.Listen();
        // 创建套接字对应的私自缓冲区
        Data *p = new Data(&_epoll, &_server);
        _map.emplace(std::pair<int, Data *>(_sock, p));
        // 放进epoll模型
        _epoll.Epoll_Ctl(EPOLL_CTL_ADD, _sock, EPOLLET | EPOLLIN);
    }
    void Start()
    {
        while(true)
        {
            epoll_event event[EPOLL_EVENT_NUM];
            int n = _epoll.Epoll_Wait(event, EPOLL_EVENT_NUM, TIMEOUT);
            switch(n)
            {
            case 0:
                std::cout << "timeout..." << std::endl;
                break;
            case -1:
                std::cout << "Epoll_Wait fail:" << strerror(errno) << errno << std::endl;
                break;
            default:
                _fun.HandlEvent(event, _sock, n, _map);
                break;
            }
        }
    }
private:
    int _sock;
    Sock _server;
    Epoll _epoll;
    Funtion _fun;
    std::unordered_map<int, Data *> _map;
};